package com.putao.spider;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.putao.entity.ZhihuData;
import com.putao.utils.HttpUtils;

import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.JsonPathSelector;
import us.codecraft.webmagic.utils.UrlUtils;

public class ZhihuTopicPost {

	public static List<ZhihuData> post(String catId, String catName) {
		List<ZhihuData> tempList = new ArrayList<>();

		Map<String, String> map = new HashMap<>();
		map.put("method", "next");
		int offset = 20;
		while (true) {
			map.put("params", "{\"topic_id\":" + catId + ",\"offset\":" + offset
					+ ",\"hash_id\":\"b1e717187242546981754101d51fc89b\"}");
			String result = HttpUtils.send("https://www.zhihu.com/node/TopicsPlazzaListV2", map, "UTF-8");
			result = UrlUtils.fixAllRelativeHrefs(
					new Html(new JsonPathSelector("$.msg").selectList(result).toString()).toString(),
					"https://www.zhihu.com/");
			List<String> topicIds = new Html(result).xpath("//body/div/div[@class=\"blk\"]/a[@target=\"_blank\"]")
					.links().all();
			List<String> topicNames = new Html(result)
					.xpath("//body/div/div[@class=\"blk\"]/a[@target=\"_blank\"]/strong/text()").all();
			if (topicIds.isEmpty()) {
				break;
			} else {
				offset += 20;
				// tempList.addAll(temp);
				for (int i = 0; i < topicIds.size(); i++) {
					ZhihuData zhihuData = new ZhihuData(catId, catName, topicIds.get(i), topicNames.get(i), null, null);
					tempList.add(zhihuData);
				}
			}
		}

		return tempList;
	}

}